package com.memory.modules.business.service.user.impl;

import com.memory.common.data.PageSort;
import com.memory.modules.business.domain.user.Account;
import com.memory.modules.business.domain.user.IssueRecord;
import com.memory.modules.business.repository.user.AccountRepository;
import com.memory.modules.business.repository.user.IssueRecordRepository;
import com.memory.modules.business.service.user.IssueRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * @PackageName: com.memory.modules.business.service.user.impl
 * @ClassName: IssueRecordServiceImpl
 * @Description:
 * @author: zhuguangxun
 * @date 2021/3/10
 */
@Service
@RequiredArgsConstructor
public class IssueRecordServiceImpl implements IssueRecordService {

    private final AccountRepository accountRepository;

    private final IssueRecordRepository issueRecordRepository;

    @Override
    public IssueRecord create(IssueRecord record) {
        return issueRecordRepository.save(record);
    }

    @Override
    public Page<IssueRecord> findPage(Example<IssueRecord> example) {
        final PageRequest pageRequest = PageSort.pageRequest();
        return issueRecordRepository.findAll(example, pageRequest);
    }

    @Override
    public Optional<IssueRecord> create(String openId, String message) {
        final Account account = accountRepository.findByOpenId(openId);
        IssueRecord issueRecord = new IssueRecord();
        issueRecord.setAccountId(account == null ? null : account.getId());
        issueRecord.setMsg(message);
        issueRecord.setCreateDate(new Date());
        return Optional.ofNullable(issueRecordRepository.save(issueRecord));
    }
}
